package com.jpress.control;

import java.util.Calendar;
import java.util.List;

import com.jpress.dao.DAOComentario;
import com.jpress.dao.DAOPost;
import com.jpress.dao.DAOUsuario;
import com.jpress.model.Comentario;
import com.jpress.model.Post;


public class ComentarioControl {
	DAOComentario daoComentario = new DAOComentario();
	DAOUsuario daoUsuario = new DAOUsuario();
	DAOPost daoPost = new DAOPost();

	public int getComentarioQtde() {
		return (int) this.daoComentario.findAll().size();
	}


	public List<Comentario> meusComentarios(int id) {
		String query = "SELECT c FROM Comentario c WHERE c.autor.id = '" + String.valueOf(id) + "' ORDER BY c.data DESC";
		return this.daoComentario.findAllWithMaxWithQuery(query, 5);

	}

	public Comentario getComentarioById(int id) {
		return this.daoComentario.findById(id);
	}

	@SuppressWarnings("unchecked")
	public List<Comentario> getComentariosByBlogId(int id) {
		String query = "SELECT c FROM Comentario c WHERE c.post.id = '" + String.valueOf(id) + "' ";
		return this.daoComentario.findAllByQuery(query);
	}


	public boolean cadastrarComentario(Comentario novoComentario, int id, int idpost) {
		try {
			novoComentario.setData(Calendar.getInstance());
			novoComentario.setPost(daoPost.findById(idpost));
			novoComentario.setAutor(daoUsuario.findById(id));
			this.daoComentario.begin();
			this.daoComentario.persist((Comentario) novoComentario);
			this.daoComentario.commit();
			return true;
		} catch (Exception e) {
			return false;
		} finally{
			this.daoComentario.close();
		}
	}
}
